package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IdWorker idWorker;

    // 保存发布视频
    public String save(Video video) {
        // 1:设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        // 2:调用方法保存对象
        template.save(video);
        // 3:返回对象ID
        return video.getId().toHexString();
    }

    // 根据vid查询数据列表
    public List<Video> findVideosByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").is(vids));
        List<Video> videoList = template.find(query, Video.class);
        return videoList;
    }

    // 根据分页查询数据列表
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return template.find(query, Video.class);
    }

    // 关注用户
    public void saveFocusUser(FocusUser focusUser) {
        // 判断数据库中是否有记录,如果没有就保存
        Query query = Query.query(Criteria.where("userId").is(focusUser.getUserId())
                .and("followUserId").is(focusUser.getFollowUserId()));

        FocusUser user = template.findOne(query, FocusUser.class);
        if (user == null) {
            focusUser.setCreated(System.currentTimeMillis());
            template.save(focusUser);
        }
    }

    // 取消关注
    public void deleteUserUnFocus(Long followUserId, Long userId) {
        // 根据用户id和关注的用户id进行筛选
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        template.remove(query, FocusUser.class);
    }

    // 视频点赞,评论功能,喜欢功能, 通用型方法
    public Integer save(Comment comment) {
        // 1:查询视频
        Video video = template.findById(comment.getPublishId(), Video.class);
        // 2:向comment表设置被发布视频人的属性
        if (video != null) {
            comment.setPublishUserId(video.getUserId());
        }
        // 3:保存到数据库
        template.save(comment);
        // 4:更新动态表中对应的字段

        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        // 设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        // 获得更新后的最新数据
        options.returnNew(true);
        // 更新某个字段,并且返回更新后的数据
        // 1:查询条件, 2:要更新的字段和对应的值, 3:更新的设置,拿到最新的结果, 4:当前操作实体类的字节码对象
        Video modify = template.findAndModify(query, update, options, Video.class);
        // 5:获取最新的评论,点赞,喜欢数量,并且返回
        return modify.newCount(comment.getCommentType());
    }

    // 查询视频评论列表
    public List<Comment> findVideoComments(String videoId, CommentType comment, Integer page, Integer pagesize) {
        // 根据视频id和评论类型,按照评论时间进行分页查询
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(videoId))
                        .and("commentType").is(comment.getType()))
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return template.find(query, Comment.class);
    }

    // 取消点赞
    public Integer delete(Comment comment) {
        // 1:删除comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        template.remove(query, Comment.class);
        // 2:修改动态表中的总数量
        Query videoQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", -1);
        } else {
            update.inc("loveCount", -1);
        }
        // 设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);  // 获得更新后的最新数据
        // 更新某个字段,并且返回更新后的数据
        // 1:查询条件, 2:要更新的字段和对应的值, 3:更新的设置,拿到最新的结果, 4:当前操作实体类的字节码对象
        Video modify = template.findAndModify(videoQuery, update, options, Video.class);
        // 5:获取最新的点赞数量,并且返回
        return modify.newCount(comment.getCommentType());
    }

    // 根据用户id分页查询视频列表
    public List<Video> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = template.find(query, Video.class);
        return list;
    }
}


